# Contributor: Carlo Landmeter <clandmeter@alpinelinux.org>
# Maintainer: Jakub Jirutka <jakub@jirutka.cz>
pkgname=luarocks
pkgver=3.9.2
pkgrel=1
pkgdesc="Deployment and management system for Lua modules"
url="https://luarocks.org/"
arch="noarch"
license="MIT"
depends="curl"
source="https://luarocks.org/releases/$pkgname-$pkgver.tar.gz
	prefer-curl-to-wget.patch
	config.lua
	"

_lua_versions="5.1 5.2 5.3 5.4"
for _v in $_lua_versions; do
	makedepends="$makedepends lua$_v-dev"
	subpackages="$subpackages $pkgname${_v}:_subpackage"
	triggers="$triggers $pkgname$_v.trigger=/usr/lib/luarocks/rocks-$_v:/usr/lib/luarocks/rocks-common"
done

prepare() {
	default_prepare

	# Create builddir for each Lua version.
	local lver; for lver in $_lua_versions; do
		cp -r "$builddir" "$builddir-$lver"
	done
}

build() {
	local lver; for lver in $_lua_versions; do
		msg "Building for Lua $lver..."
		cd "$builddir-$lver"

		./configure \
			--prefix=/usr \
			--sysconfdir=/etc \
			--rocks-tree=/usr/local \
			--lua-version="$lver" \
			--with-lua-include="$(pkg-config --variable=includedir lua$lver)" \
			--with-lua-lib="$(pkg-config --variable=libdir lua$lver)"
		make
	done
}

package() {
	mkdir -p "$pkgdir"
}

_subpackage() {
	local lver="${subpkgname#$pkgname}"
	pkgdesc="Deployment and management system for Lua $lver modules"
	install_if="lua$lver $pkgname=$pkgver-r$pkgrel"
	depends="$depends lua$lver"

	cd "$builddir-$lver"

	make install DESTDIR="$subpkgdir"

	# Move default scripts which conflict per Lua version.
	mv "$subpkgdir"/usr/bin/luarocks "$subpkgdir"/usr/bin/luarocks-"$lver"
	mv "$subpkgdir"/usr/bin/luarocks-admin "$subpkgdir"/usr/bin/luarocks-admin-"$lver"

	# Set the correct Lua version.
	sed -i "s/env lua/env lua$lver/" \
		"$subpkgdir"/usr/bin/luarocks-$lver \
		"$subpkgdir"/usr/bin/luarocks-admin-$lver

	# Config based on:
	#   https://github.com/luarocks/luarocks/wiki/Integrating-distro-modules-with-LuaRocks
	install -D -m 644 "$srcdir"/config.lua "$subpkgdir"/etc/$pkgname/config-$lver.lua
}

sha512sums="
7e93164bdcf35338e993822931a8e59957ab69c6e23236a7a075649c2f7cd173305c4ca6e9d115fc5e282cb76c21754d7adac92b21885006e5ee3bc06a9d0059  luarocks-3.9.2.tar.gz
e8ea793df118bd9b871d44706d9b51b95e0ae437dd4262df405c2ac45529f34cf88e06f1ba857abb4ce37b7df0e15777aba104c740709d2485d6579eadf3c032  prefer-curl-to-wget.patch
5845d5643c3eeb6d4af6d919a588c5253c91e6a0b278116b4cd855437fc48ac64970fd3ef758c135bc0536ddc1aaa16b01c50e33c864f59aeef1ccced0d01d82  config.lua
"
